﻿using System;
using System.IO;
using System.Text;
using System.Configuration;
using System.Threading;
using System.Windows.Forms;

using DreamCube.WinForm.Common;
using DreamCube.Foundation.Serialization;
using DreamCube.Foundation.Basic.Utility;
using DreamCube.Framework.Utilities.BasicObject;

namespace TeqcHelper.UI
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 获取配置文件的目录
        /// </summary>
        /// <returns></returns>
        protected static String GetConfigFilePath()
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.config");
        }

        /// <summary>
        /// 保存配置信息
        /// </summary>
        protected void SaveConfig()
        {
            try
            {
                //Config c = new Config
                //{
                //    CommandText = textBox3.Text,
                //    OutputPath = textBox2.Text,
                //    InputPath = textBox1.Text
                //};
                ////ConfigurationManager.AppSettings["configData"] = MyJson.Serialize(c);
                ////ConfigurationManager.RefreshSection("appSettings");
                String configFilePath = GetConfigFilePath();
                //MyIO.Write(configFilePath, MyJson.Serialize(c), false);
                MyControl.ControlInvoke(this, new Action(() => {
                    ObjectX obj = ObjectXHelperEx.CreateObjFromForm(this);
                    obj.SaveJSONToFile(configFilePath);
                }));
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }

        /// <summary>
        /// 配置窗体程序
        /// </summary>
        protected void ConfigForm()
        {
            try
            {
                //String configJSON = ConfigurationManager.AppSettings["configData"];
                //String configJSON = "";
                //if (MyIO.TryReadText(GetConfigFilePath(), Encoding.UTF8, out configJSON) && !String.IsNullOrEmpty(configJSON))
                //{
                //    Config configObj = MyJson.Deserialize<Config>(configJSON);
                //    textBox1.Text = configObj.InputPath;
                //    textBox2.Text = configObj.OutputPath;
                //    textBox3.Text = configObj.CommandText;
                //    radioButton1.Checked = configObj.KeepOldName;
                //    radioButton2.Checked = configObj.GenerateNewName;
                //}
                MyControl.ControlInvoke(this, new Action(() => {
                    ObjectXHelperEx.WriteObjToFormByJSONFile(GetConfigFilePath(), this);
                }));
                //生成下拉选择
                MyComboBox.AddItems(comboBox1, ConfigurationManager.AppSettings["fileNamePrefix"]);
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }

        /// <summary>
        /// 选择源文件目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog1.SelectedPath;
               
            }
        }

        /// <summary>
        /// 选中文件名前缀
        /// </summary>
        private void SelectFileNamePrefix()
        {
            String pathName = MyString.RightOfLast(textBox1.Text, "\\");
            MyComboBox.SelectItem(comboBox1, pathName);
        }

        /// <summary>
        /// 选择输出目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox2.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        /// <summary>
        /// 调用命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(textBox1.Text))
            {
                MessageBoxEx.Show(this, "源文件目录不能为空！", "提醒");
                return;
            }
            if (String.IsNullOrEmpty(textBox2.Text))
            {
                MessageBoxEx.Show(this, "输出目录不能为空！", "提醒");
                return;
            }
            if (String.IsNullOrEmpty(textBox3.Text))
            {
                MessageBoxEx.Show(this, "命令不能为空！", "提醒");
                return;
            }
            //if (textBox1.Text == textBox2.Text)
            //{
            //    MessageBoxEx.Show(this, "源文件目录和输出文件目录不能是同一个的！", "提醒");
            //    return;
            //}
            String fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BasicFiles\\teqc.exe");
            if (IsNeedFileExist(fileName))
            {
                String sourcePathName = MyString.RightOfLast(textBox1.Text,"\\");
                String outputPath = Path.Combine(textBox2.Text,sourcePathName);
                ThreadPool.QueueUserWorkItem(new WaitCallback((o) =>
                {
                    try
                    {
                        String[] aInputParams = o as String[];
                        DoExecCommand(aInputParams);
                    }
                    catch (Exception ex)
                    {
                        MyLog.MakeLog(ex);
                    }
                }), new String[] { textBox1.Text, outputPath, textBox3.Text, fileName });
                MyWaitingForm.Show(this, "正在处理命令", "提醒", false);
            }
            else
            {
                MessageBoxEx.Show(this, "您好，找不到teqc.exe文件哦！", "提醒");
            }
        }

        /// <summary>
        /// 执行 RINEX文件改变采样率
        /// </summary>
        /// <param name="aInputParams"></param>
        private void DoExecCommand(String[] aInputParams)
        {
            try
            {
                SaveConfig();
                if (aInputParams != null)
                {
                    String[] files = null;
                    StringBuilder logBuilder = new StringBuilder();
                    if (MyIO.TryGetFiles(aInputParams[0], out files, "*.*o", SearchOption.AllDirectories))
                    {
                        String commandText = aInputParams[2].Trim();
                        if (commandText.StartsWith("teqc")) commandText = commandText.Substring(4);
                        String commandTemplate = "{0} {1} {2}>{3}";
                        String logTemplate = "转换文件{0}结果：{1}{2}";
                        for (Int32 i = 0; i < files.Length; i++)
                        {
                            String filePath = files[i];
                            String fileName = MyString.RightOfLast(filePath, "\\");
                            //获取到输出的目录
                            String outputDir = MyString.LeftOfLast(MyString.Right(filePath, aInputParams[0]), fileName);
                            if (outputDir.StartsWith("\\")) outputDir = outputDir.Substring(1);
                            //确保输出目录存在
                            outputDir = Path.Combine(aInputParams[1], outputDir);
                            MyIO.EnsurePath(outputDir);

                            String outputFile = "";
                            Boolean keepOldFileName = MyControl.ControlInvoke<Boolean>(radioButton1, new Func<Boolean>(() => { return radioButton1.Checked; }));
                            //保留文件名不便
                            if (keepOldFileName)
                            {
                                outputFile = Path.Combine(outputDir, fileName);
                            }
                            else
                            {
                                outputFile = Path.Combine(outputDir, GetOutPutFileName(fileName));
                                //保证文件名不能为空
                                if (String.IsNullOrEmpty(outputFile)) outputFile = Path.Combine(outputDir, fileName);
                            }
                            String msg = MyCMD.RunCmd(new String[] { String.Format(commandTemplate, aInputParams[3], commandText, filePath, outputFile) });

                            logBuilder.AppendFormat(logTemplate, fileName, msg, Environment.NewLine + Environment.NewLine);
                        }
                    }
                    String outputLogFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt");
                    MyIO.Write(outputLogFile, logBuilder.ToString(), false);

                    MyWaitingForm.WaitingForm.Invoke(new Action<Object>((o) =>
                    {
                        MessageBoxEx.Show(MyWaitingForm.WaitingForm, "执行命令完毕，详细情况可以查看log.txt文件！", "提醒");
                    }), "");
                }
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
            finally
            {
                MyWaitingForm.WaitingForm.Invoke(new Action<Object>((o) =>
                {
                    MyWaitingForm.WaitingForm.Hide();
                }), "");
            }
        }

        /// <summary>
        /// 获取输出文件名
        /// </summary>
        /// <returns></returns>
        private String GetOutPutFileName(String fileName)
        {
            try
            {
                String prefix = MyControl.ControlInvoke<String>(comboBox1, new Func<String>(() => { return comboBox1.SelectedItem.ToString(); }));
                String[] parts = MyString.SplitEx(fileName, 2);
                String fileExtension = MyString.RightOfLast(fileName, ".");
                DateTime date = new DateTime(Int32.Parse("20" + parts[0]), Int32.Parse(parts[1]), Int32.Parse(parts[2]));
                return String.Format("{0}{1}0.{2}",prefix, MyNumber.Format(date.DayOfYear, 0, 3), fileExtension);
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
            return String.Empty;
        }

        /// <summary>
        /// 判断所需要的文件是否存在
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private Boolean IsNeedFileExist(String filePath)
        {
            try
            {
                return File.Exists(filePath);
            }
            catch (IOException)
            {
                return false;
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
            return false;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            ConfigForm();
        }

        /// <summary>
        /// 选中生成新文件的时候，启用下拉框编辑性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            comboBox1.Enabled = radioButton2.Checked;
            if (comboBox1.Enabled)
            {
                SelectFileNamePrefix();
            }
        }
    }
}
